<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Gds\VenteBundle\Entity\Caisse;
use Gds\VenteBundle\Form\CaisseType;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Ps\PdfBundle\Annotation\Pdf;
use Gds\VenteBundle\Entity\TicketCaisse;
use Gds\VenteBundle\Entity\LigneTicketCaisse;
use \DateTime;
use Gds\VenteBundle\Entity\ReglementClient;
use Gds\VenteBundle\Entity\LigneReglementClient;
use Gds\VenteBundle\Entity\BonLivraisonClient;
use Gds\VenteBundle\Entity\LigneBonLivraisonClient;
use Gds\VenteBundle\Entity\CategorieRemise;
use Gds\VenteBundle\Entity\Acompte;
use Gds\AchatBundle\Entity\StockAchat;

class PointVenteController extends Controller {

    public function getFormAccompteAction() {
        $client = $this->getDoctrine()->getManager()->getRepository('GdsVenteBundle:Client')->find($this->getRequest()->get('id'));
        return $this->render('GdsVenteBundle:Reglement:accompte.html.twig', array('client' => $client));
    }

    public function saveAccompteAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $client_id = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        if ($this->get('security.context')->isGranted('ROLE_ADMIN'))
            $session = $em->getRepository('GdsVenteBundle:SessionCaisse')->findOneBy(array('caisse' => $request->get('caisse_id'), 'date_fermeture' => null));
        else
            $session = $em->getRepository('GdsVenteBundle:SessionCaisse')->findOneBy(array('user' => $this->getUser(), 'date_fermeture' => null));
        $departement = $this->getUser()->getDepartement();

        $ticket = new TicketCaisse();
        $ticket->setClient($client);
        $ticket->setDate(new DateTime(date('Y-m-d H:i:s')));
        $ticket->setSession($session);
        $em->persist($ticket);
        $ref = $societe->getPrefixeTicket();
        $ref_num = $societe->getNumeroTicket();
        $societe->setNumeroTicket($ref_num + 1);
        $ticket->setReference($ref . ' ' . $ref_num);
        $ticket->setReste(0);
        $ticket->setMontantBlancTtc(0);
        $reglement = new ReglementClient();
        $reglement->setClient($client);
        $reglement->setDate(new DateTime(date('Y-m-d')));
        $reglement->setHeure($request->get('heure'));
        $reglement->setSessionCaisse($session);
        $reglement->setUser($this->getUser());
        $reglement->setReference($societe->getPrefixeReglement() . ' ' . $societe->getNumeroReglement());
        $societe->setNumeroReglement($societe->getNumeroReglement() + 1);
        $paiements = json_decode($request->get('accomptes'));

        $total = 0;
        foreach ($paiements as $paiement) {
            $ligne = new LigneReglementClient();
            $ligne->setType($paiement->type);
            if ($ligne->getType() != 'Espece') {
                $tab = date_parse_from_format('d/m/Y', $paiement->date);
                $ligne->setDateEcheance(new \DateTime(date('Y-m-d', mktime(0, 0, 0, $tab['month'], $tab['day'], $tab['year']))));
                $ligne->setCompteBancaire($em->getRepository('GdsAchatBundle:CompteBancaire')->find($paiement->compte));
                $ligne->setNumeroPiece($paiement->numero);
            }
            $ligne->setMontant($paiement->montant);
            $ligne->setTicket($ticket);
            $total = $total + $paiement->montant;
            $reglement->addLigne($ligne);
        }
        $reglement->setMontantTtc($total);
        $em->persist($reglement);
        $ticket->setMontantBlancTtc(0);
        $ticket->setMontantNoirTtc(0);
        $acompte = new Acompte();
        $acompte->setClient($client);
        $acompte->setDate(new \DateTime(date('Y-m-d')));
        $acompte->setHeure($request->get('heure'));
        $acompte->setMontant($total);
        $client->setSolde($client->getSolde() - $total);
        $em->persist($client);
        $acompte->setReste($acompte->getMontant());
        $acompte->setUser($this->getUser());
        $ref = $societe->getPrefixeAcompte();
        $num = $societe->getNumeroAcompte();
        $acompte->setReference($ref . '-' . $num);
        $ticket->setAcompte($acompte);
        $societe->setNumeroAcompte($societe->getNumeroAcompte() + 1);
        $em->persist($societe);
        $em->persist($acompte);
        $em->flush();
        $tab = array();
        $tab['success'] = true;
        $tab['acompte_reference'] = $acompte->getReference();
        $tab['acompte_montant'] = $acompte->getReste();
        return new Response(json_encode($tab));
    }

    public function getAcoompteClientAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $name_startsWith = $request->get('name_startsWith');
        $ids = $request->get('ids');
        $acomptes = $em->getRepository('GdsVenteBundle:Acompte')->getAcompteClientNonRegler(1, $name_startsWith, $ids);
        $results = array();
        if (count($acomptes) > 0) {
            foreach ($acomptes as $acompte) {
                $tab = array();
                $tab['reste'] = $acompte->getReste();
                $tab['id'] = $acompte->getId();
                $tab['reference'] = $acompte->getReference();
                $results[] = $tab;
            }
        }
        $tabs['acompts'] = $results;
        return new Response(json_encode($tabs));
    }

    public function transformeAcompteAction() {
        $request = $this->getRequest();
        $client_id = $request->get('client_id');
        $heure = $request->get('heure');

        $em = $this->getDoctrine()->getEntityManager();
        $ticket = $em->getRepository('GdsVenteBundle:TicketCaisse')->find($request->get('ticket_id'));

        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        $acompte = new Acompte();
        $acompte->setClient($client);
        $acompte->setDate(new \DateTime(date('Y-m-d')));
        $acompte->setHeure($heure);
        $acompte->setMontant($request->get('montant'));
        $client->setSolde($client->getSolde() - $request->get('montant'));
        $em->persist($client);
        $acompte->setReste($acompte->getMontant());
        $acompte->setUser($this->getUser());
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $ref = $societe->getPrefixeAcompte();
        $num = $societe->getNumeroAcompte();
        $acompte->setReference($ref . '-' . $num);
        $societe->setNumeroAcompte($societe->getNumeroAcompte() + 1);
        $em->persist($societe);
        $em->persist($acompte);
        $ticket->setAcompte($acompte);
        $em->flush();
        $tab = array();
        $tab['success'] = true;
        $tab['acompte_reference'] = $acompte->getReference();
        $tab['acompte_montant'] = $acompte->getReste();
        return new Response(json_encode($tab));
    }

    public function devisAction() {
        $id = $this->getRequest()->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $client = $devis->getClient();
        $result = array();
        $k = 0;
        foreach ($devis->getLignesDevis() as $ligne) {
            $article = $ligne->getArticle();
            if ($article->getIsSupprimer() == false) {
                $result[$k]['designation'] = $article->getDesignation();
                $result[$k]['reference'] = $article->getReference();
                $result[$k]['tva'] = $ligne->getTauxTva();
                $result[$k]['remise'] = $ligne->getTauxRemise();
                $result[$k]['remise_max'] = $article->getRemiseMax();
                $result[$k]['prix_vente'] = $ligne->getPrixUnitaireHt();
                $result[$k]['quantite'] = $ligne->getQuantite();
                $result[$k]['prix_vente_min_ttc'] = $ligne->getPrixUnitaireHt() * (1 + $ligne->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                $name = $article->getReference() . ' : ' . $article->getDesignation() . ' : ' . $article->getCodeBarre();
                $result[$k]['name'] = $name;
                $result[$k]['id'] = $article->getId();
                $result[$k]['unite']['libelle'] = $article->getUnite()->getCode();
                $result[$k]['unite']['chiffre_virgule'] = $article->getUnite()->getChiffreVirgule();
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $this->getUser()->getDepartement()));
                $result[$k]['quantite_stock'] = $stock->getTotalQuantite();
                $result[$k]['quantite_min'] = $stock->getQuantiteMin();
                $k++;
            }
        }
        return new Response(json_encode($result));
    }

    public function chargeDevisAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $client_id = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        $num = $request->get('numero');
        $date1 = $request->get('date1');
        $date2 = $request->get('date2');
        $heure1 = $request->get('heure1');
        $heure2 = $request->get('heure2');
        $ttc1 = $request->get('ttc1');
        $ttc2 = $request->get('ttc2');
        $query = $em->getRepository('GdsVenteBundle:Devis')->getResultPointVente($num, $client, $date1, $date2, $heure1, $heure2, $ttc1, $ttc2);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );

        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:PointVente:page_liste_devis.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsVenteBundle:PointVente:liste_devis.html.twig', array('pagination' => $pagination));
    }

    public function retourAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $client_id = $request->get('client_id');
    }

    public function reglementEffetAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $client_id = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        return $this->render('GdsVenteBundle:PointVente:reglementEffet.html.twig', array('client' => $client));
    }

    public function reglementChequeAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $client_id = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        return $this->render('GdsVenteBundle:PointVente:reglementCheque.html.twig', array('client' => $client));
    }

    public function saveTicketAction() {
        $request = $this->getRequest();
        $test = true;
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $client_id = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        if ($this->get('security.context')->isGranted('ROLE_ADMIN'))
            $session = $em->getRepository('GdsVenteBundle:SessionCaisse')->findOneBy(array('caisse' => $request->get('caisse_id'), 'date_fermeture' => null));
        else
            $session = $em->getRepository('GdsVenteBundle:SessionCaisse')->findOneBy(array('user' => $this->getUser(), 'date_fermeture' => null));
        $departement = $this->getUser()->getDepartement();
        $lignes = $request->get('lignes');
        $lignes = json_decode($lignes);
        $retours = $request->get('retours');
        $retours = json_decode($retours);
        $ticket = new TicketCaisse();
        $ticket->setClient($client);
        $ticket->setDate(new DateTime(date('Y-m-d H:i:s')));
        $ticket->setSession($session);
        $em->persist($ticket);
        $montant_bl_ttc = 0;
        $montant_noir_ttc = 0;
        $montant_recu = $request->get('montant_recu');
        foreach ($lignes as $ligne) {

            $article = $em->getRepository('GdsArticleBundle:Article')->find($ligne->id);
            $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
            $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
            $quantite = $ligne->quantite;
            $quantite_blanc = 0;
            $quantite_noir = 0;
            $prix_achat_ttc = 0;
            $i = 0;
            while ($quantite > 0 && $i < count($stock_achat)) {
                if ($quantite < $stock_achat[$i]->getQuantite()) {
                    $stock_achat[$i]->setQuantite($stock_achat[$i]->getQuantite() - $quantite);
                    $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $quantite;
                    if ($stock_achat[$i]->getIsNoir())
                        $quantite_noir += $quantite;
                    else
                        $quantite_blanc += $quantite;
                    $quantite = 0;
                } else {
                    $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $stock_achat[$i]->getQuantite();
                    if ($stock_achat[$i]->getIsNoir())
                        $quantite_noir += $stock_achat[$i]->getQuantite();
                    else
                        $quantite_blanc += $stock_achat[$i]->getQuantite();
                    $quantite -= $stock_achat[$i]->getQuantite();
                    $em->remove($stock_achat[$i]);
                }
                $i++;
            }
            if ($quantite > 0) {
                $prix_achat_ttc += $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100) * $quantite;
                $q_n = $stock->getQuantiteNoir() - $quantite_noir;
                $q_b = $stock->getQuantiteBlanc() - $quantite_blanc;
                if ($quantite <= $q_n || $q_b <= 0) {
                    $quantite_noir += $quantite;
                } else {
                    if ($q_n > 0) {
                        $quantite_noir += $q_n;
                        $quantite -=$q_n;
                    }
                    if ($q_b >= $quantite) {
                        $quantite_blanc +=$quantite;
                    } else {
                        $quantite_blanc +=$q_b;
                        $quantite_noir = $quantite_noir + $quantite - $q_b;
                    }
                }
            }
            $stock->setQuantiteBlanc($stock->getQuantiteBlanc() - $quantite_blanc);
            $stock->setQuantiteNoir($stock->getQuantiteNoir() - $quantite_noir);
            $prix_achat_ttc /= $ligne->quantite;
            $prix_vente = $ligne->prix_vente;
            $taux_tva = $ligne->tva;
            $remise = $ligne->remise;
            $prix_vente_ttc = $prix_vente * (1 + $taux_tva / 100) * (1 - $remise / 100);
            $montant_bl_ttc += $prix_vente_ttc * $quantite_blanc;
            $montant_noir_ttc += $prix_vente_ttc * $quantite_noir;
            $l = new LigneTicketCaisse();
            $l->setStock($stock);
            $l->setQuantiteBlanc($quantite_blanc);
            $l->setQuantiteNoir($quantite_noir);
            $l->setQuantiteRetour(0);
            $l->setPrixUnitaireHt($prix_vente);
            $l->setPrixAchatTtc($prix_achat_ttc);
            $l->setTauxRemise($remise);
            $l->setTauxTva($taux_tva);
            $em->persist($stock);
            $ticket->addLigne($l);
            if ($client->getId() != 1) {
                $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                if ($categorie_remise != null)
                    $categorie_remise->setRemise($remise);
                else {
                    $categorie_remise = new CategorieRemise();
                    $categorie_remise->setArticle($article);
                    $categorie_remise->setClient($client);
                    $categorie_remise->setRemise($remise);
                    $em->persist($categorie_remise);
                }
            }
        }
        foreach ($retours as $retour) {
            $article = $em->getRepository('GdsArticleBundle:Article')->find($retour->id);
            $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));

            $quantite = $retour->quantite;
            $prix_vente = $retour->prix_vente;
            $taux_tva = $retour->tva;
            $remise = $retour->remise;
            $prix_vente_ttc = $prix_vente * (1 + $taux_tva / 100) * (1 - $remise / 100);
            $prix_achat_ttc = $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100);
            if ($retour->noir == 1) {
                $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => true, 'prix_achat_ttc' => $prix_vente_ttc));
                $stock->setQuantiteNoir($stock->getQuantiteNoir() + $quantite);
                if (count($stock_achat) > 0) {
                    $stock_achat[0]->setQuantite($stock_achat[0]->getQuantite() + $quantite);
                    $em->persist($stock_achat[0]);
                } else {
                    $stock_achat = new StockAchat();
                    $stock_achat->setIsNoir(true);
                    $stock_achat->setPrixAchatTtc($prix_vente_ttc);
                    $stock_achat->setQuantite($quantite);
                    $stock_achat->setStock($stock);
                    $em->persist($stock_achat);
                }
            } else {
                $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => FALSE, 'prix_achat_ttc' => $prix_vente_ttc));
                $stock->setQuantiteBlanc($stock->getQuantiteBlanc() + $quantite);
                if (count($stock_achat) > 0) {
                    $stock_achat[0]->setQuantite($stock_achat[0]->getQuantite() + $quantite);
                    $em->persist($stock_achat[0]);
                } else {
                    $stock_achat = new StockAchat();
                    $stock_achat->setIsNoir(FALSE);
                    $stock_achat->setPrixAchatTtc($prix_vente_ttc);
                    $stock_achat->setQuantite($quantite);
                    $stock_achat->setStock($stock);
                    $em->persist($stock_achat);
                }
            }
            $montant_noir_ttc -= $prix_vente_ttc * $quantite;
            $l = new LigneTicketCaisse();
            $l->setStock($stock);
            $l->setQuantiteBlanc(0);
            $l->setQuantiteNoir(0);
            $l->setQuantiteRetour($quantite);
            $l->setPrixUnitaireHt($prix_vente);
            $l->setPrixAchatTtc($prix_achat_ttc);
            $l->setTauxRemise($remise);
            $l->setTauxTva($taux_tva);
            $ticket->addLigne($l);
            $em->persist($stock);
        }
        $ref = $societe->getPrefixeTicket();
        $ref_num = $societe->getNumeroTicket();
        $societe->setNumeroTicket($ref_num + 1);
        $ticket->setReference($ref . ' ' . $ref_num);
        if ($montant_recu > $montant_bl_ttc + $montant_noir_ttc || $request->get('montat_ttc') < 0)
            $ticket->setReste(0);
        else
        if ($montant_recu == 0)
            $ticket->setReste($montant_bl_ttc + $montant_noir_ttc);
        else
            $ticket->setReste($montant_bl_ttc + $montant_noir_ttc - $montant_recu);
        $ticket->setMontantBlancTtc($montant_bl_ttc);
        $ticket->setMontantNoirTtc($montant_noir_ttc);
        $client->setSolde($client->getSolde() + $ticket->getReste());
        if ($request->get('montat_ttc') > 0) {
            if ($montant_recu > 0) {
                $reglement = new ReglementClient();
                $reglement->setClient($client);
                $reglement->setDate(new DateTime(date('Y-m-d')));
                $reglement->setHeure($request->get('heure'));
                if ($montant_recu > $montant_bl_ttc + $montant_noir_ttc)
                    $reglement->setMontantTtc($montant_bl_ttc + $montant_noir_ttc);
                else
                    $reglement->setMontantTtc($montant_recu);
                $reglement->setReference($societe->getPrefixeReglement() . ' ' . $societe->getNumeroReglement());
                if ($request->get('paiements')) {
                    $paiements = json_decode($request->get('paiements'));
                    $paiements = $paiements->paiements;
                    $j = 0;
                    $k = -1;
                    $acomptes = array();
                    $total = 0;

                    while ($j < count($paiements)) {
                        if ($paiements[$j]->type == 'Acompte') {
                            $acomptes[] = $paiements[$j];
                        } else {
                            $ligne = new LigneReglementClient();
                            $ligne->setType($paiements[$j]->type);
                            $m = 0;
                            if ($ligne->getType() != 'Espece') {
                                $tab = date_parse_from_format('d/m/Y', $paiements[$j]->date);
                                $ligne->setDateEcheance(new \DateTime(date('Y-m-d', mktime(0, 0, 0, $tab['month'], $tab['day'], $tab['year']))));
                                $ligne->setCompteBancaire($em->getRepository('GdsAchatBundle:CompteBancaire')->find($paiements[$j]->compte));
                                $ligne->setNumeroPiece($paiements[$j]->numero);
                            } else {
                                $k = $j;
                            }
                            $ligne->setMontant($paiements[$j]->montant);
                            $ligne->setTicket($ticket);
                            $total = $total + $paiements[$j]->montant;
                            $reglement->addLigne($ligne);
                        }
                        $j++;
                    }
                    $count = count($acomptes);
                    $n = 0;
                    $reste = $request->get('montat_ttc') - $total;

                    while ($count > $n && $total < $request->get('montat_ttc')) {

                        $ligne = new LigneReglementClient();
                        $ligne->setType($acomptes[$n]->type);
                        $ligne->setTicket($ticket);
                        $acompte = $em->getRepository('GdsVenteBundle:Acompte')->find($acomptes[$n]->acompte);
                        if ($acomptes[$n]->montant >= $reste) {
                            $ligne->setMontant($reste);
                            $acompte->setReste($acompte->getReste() - $reste);
                            $client->setSolde($client->getSolde() + $reste);
                            $em->persist($acompte);
                            $total = $request->get('montat_ttc');
                            $reglement->addLigne($ligne);
                            $test = false;
                        } else {
                            $ligne->setMontant($acompte->getReste());
                            $acompte->setReste(0);
                            $client->setSolde($client->getSolde() + $acompte->getReste());
                            $em->persist($acompte);
                            $total = $total + $acompte->getReste();
                            $n++;
                        }
                    }

//                    if (($montant_recu > $montant_bl_ttc + $montant_noir_ttc) && $test) {
//                        if ($k != -1)
//                            $reglement->getLignes()[$k]->setMontant($reglement->getLignes()[$k]->getMontant() - ($montant_recu - $montant_bl_ttc - $montant_noir_ttc));
//                        else {
//                            $ligne = new LigneReglementClient();
//                            $ligne->setType('Espece');
//                            $ligne->setMontant(-($montant_recu - $montant_bl_ttc - $montant_noir_ttc));
//                            $reglement->addLigne($ligne);
//                        }
//                    }
                }
            } else {
                $lr = new LigneReglementClient();
                $lr->setMontant($reglement->getMontantTtc());
                if ($request->get('type') == 'espece') {
                    $lr->setType('Espece');
                }
                if ($request->get('type') == 'cheque') {
                    $lr->setType('Cheque');
                    $info = json_decode($request->get('info'));
                    $lr->setDateEcheance(DateTime::createFromFormat('d/m/Y', $info->date_echeance));
                    $lr->setNumeroPiece($info->numero_cheque);
                    if ($info->compte_client != "") {
                        $lr->setCompteBancaire($em->getRepository('GdsAchatBundle:CompteBancaire')->find($info->compte_client));
                    } else
                        $lr->setNumeroPieceIdentite($info->numero_carte_identite);
                }
                if ($request->get('type') == 'effet') {
                    $lr->setType('Effet');
                    $info = json_decode($request->get('info'));
                    $lr->setDateEcheance(DateTime::createFromFormat('d/m/Y', $info->date_echeance));
                    $lr->setNumeroPiece($info->numero_cheque);
                    if ($info->compte_client != "") {
                        $lr->setCompteBancaire($em->getRepository('GdsAchatBundle:CompteBancaire')->find($info->compte_client));
                    } else
                        $lr->setNumeroPieceIdentite($info->numero_carte_identite);
                }
                $reglement->addLigne($lr);
            }
            $reglement->setIsCloturer(false);
            $reglement->setIsSupprimer(false);
            $reglement->setSessionCaisse($session);
            $reglement->setUser($this->getUser());
            $em->persist($reglement);
        }

        $result = array();
        if ($request->get('type')) {
            $acompte = new Acompte();
            $acompte->setClient($client);
            $acompte->setDate(new DateTime(date('Y-m-d H:i:s')));
            $acompte->setHeure($request->get('heure'));
            $acompte->setMontant(-$request->get('montat_ttc'));
            $acompte->setReste(-$request->get('montat_ttc'));
            $acompte->setUser($this->getUser());
            $ref = $societe->getPrefixeAcompte();
            $ref_num = $societe->getNumeroAcompte();
            $societe->setNumeroAcompte($ref_num + 1);
            $acompte->setReference($ref . '-' . $ref_num);
            $ticket->setAcompte($acompte);
            $result['acompte_reference'] = $acompte->getReference();
            $result['acompte_montant'] = $acompte->getMontant();
        }
        $em->persist($client);
        $em->flush();
        $result['success'] = true;
        $result['ticket_id'] = $ticket->getId();
        $result['accompte'] = true;
        if (!$test)
            $result['accompte'] = false;

        return new Response(json_encode($result));
    }

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $caisses = $em->getRepository('GdsVenteBundle:Caisse')->findBy(array('departement' => $this->getUser()->getDepartement(), 'is_active' => true));
        if (count($caisses) < 1) {
            $url = $this->generateUrl('gds_session_caisse_new', array('point_vente' => 1));
            return $this->redirect($url);
        }
        return $this->render('GdsVenteBundle:PointVente:index.html.twig', array('caisses' => $caisses));
    }

    public function getArticleAction() {
        $request = $this->getRequest();
        $raison_social = $request->query->get('client_id');
        $em = $this->getDoctrine()->getEntityManager();
        $client = $em->getRepository('GdsVenteBundle:Client')->find($raison_social);
        $familles = json_decode($request->get('familles'));
        $sous_familles = $familles->sous_familles;
        if (count($sous_familles) == 0) {
            $familles = $familles->familles;
            $all_familles = $familles;
            foreach ($familles as $famille) {
                $sous_familles = $em->getRepository('GdsArticleBundle:Famille')->findBy(array('famille_mere' => $famille, 'is_supprimer' => 0));
                foreach ($sous_familles as $sous_famille)
                    array_push($all_familles, $sous_famille->getId());
            }
            $familles = $all_familles;
        } else
            $familles = $familles->sous_familles;
        $result = array();
        $k = 0;
        foreach ($familles as $id_famille) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findByFamille($id_famille);
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $categorie_remise = null;
                    if ($client->getId() != 1)
                        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['tva'] = $article->getTauxTva();
                    if ($categorie_remise != null)
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                    else
                        $result[$k]['remise'] = $article->getRemise();
                    $result[$k]['remise_max'] = $article->getRemiseMax();
                    $result[$k]['prix_vente'] = $article->getPrixVente();
                    $result[$k]['quantite'] = 1;
                    $result[$k]['prix_vente_min_ttc'] = $article->getPrixVente() * (1 + $article->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                    $name = $article->getReference() . ' : ' . $article->getDesignation() . ' : ' . $article->getCodeBarre();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $result[$k]['unite']['libelle'] = $article->getUnite()->getCode();
                    $result[$k]['unite']['chiffre_virgule'] = $article->getUnite()->getChiffreVirgule();
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $this->getUser()->getDepartement()));
                    $result[$k]['quantite_stock'] = $stock->getTotalQuantite();
                    $result[$k]['quantite_min'] = $stock->getQuantiteMin();
                    $k++;
                }
            }
        }
        if (count($familles) == 0) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $categorie_remise = null;
                    if ($client->getId() != 1)
                        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['tva'] = $article->getTauxTva();
                    if ($categorie_remise != null)
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                    else
                        $result[$k]['remise'] = $article->getRemise();
                    $result[$k]['remise_max'] = $article->getRemiseMax();
                    $result[$k]['prix_vente'] = $article->getPrixVente();
                    $result[$k]['quantite'] = 1;
                    $result[$k]['prix_vente_min_ttc'] = $article->getPrixVente() * (1 + $article->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                    $name = $article->getReference() . ' : ' . $article->getDesignation() . ' : ' . $article->getCodeBarre();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $result[$k]['unite']['libelle'] = $article->getUnite()->getCode();
                    $result[$k]['unite']['chiffre_virgule'] = $article->getUnite()->getChiffreVirgule();
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $this->getUser()->getDepartement()));
                    $result[$k]['quantite_stock'] = $stock->getTotalQuantite();
                    $result[$k]['quantite_min'] = $stock->getQuantiteMin();
                    $k++;
                }
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getRemisesClientAction(Request $request) {
        $client = $request->request->get('client_id');
        $articles = $request->request->get('articles');
        $articles = json_decode($articles);
        $retours = $request->request->get('retours');
        $retours = json_decode($retours);
        $em = $this->getDoctrine()->getEntityManager();
        $categorie_remise_article = array();
        $categorie_remise_retour = array();
        if ($client != 1) {
            foreach ($articles as $k => $article)
                $categorie_remise_article[count($categorie_remise_article)] = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
            foreach ($retours as $k => $retour)
                $categorie_remise_retour[count($categorie_remise_retour)] = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $retour));
        }
        $result_article = array();
        foreach ($articles as $k => $art) {
            $remise = array();
            $remise['id'] = $art;
            if (count($categorie_remise_article) > $k) {
                if ($categorie_remise_article[$k] != null)
                    $remise['remise'] = $categorie_remise_article[$k]->getRemise();
                else
                    $remise['remise'] = $em->getRepository('GdsArticleBundle:Article')->find($art)->getRemise();
            } else
                $remise['remise'] = $em->getRepository('GdsArticleBundle:Article')->find($art)->getRemise();
            $result_article[] = $remise;
        }
        $result_retour = array();
        foreach ($retours as $k => $art) {
            $remise = array();
            $remise['id'] = $art;
            if (count($categorie_remise_retour) > $k) {
                if ($categorie_remise_retour[$k] != null)
                    $remise['remise'] = $categorie_remise_retour[$k]->getRemise();
                else
                    $remise['remise'] = $em->getRepository('GdsArticleBundle:Article')->find($art)->getRemise();
            } else
                $remise['remise'] = $em->getRepository('GdsArticleBundle:Article')->find($art)->getRemise();
            $result_retour[] = $remise;
        }
        $result['retour'] = $result_retour;
        $result['article'] = $result_article;
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function quantiteDepasseAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $key = $request->get('pass_quantite');
        $code = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0]->getCodeQuantite();
        if ($key != $code) {
            return new Response('failed');
        }
        return new Response('success');
    }

}
